package edu.jsnu.service.ticket.system.service.impl;

import dto.resDto.JsonData;
import edu.jsnu.service.ticket.system.service.ImageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import util.fileReader.FileUtils;
import util.fileReader.PropertiesUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class ImageServiceImpl implements ImageService {

    static String FILE_DIR_FORMAT = "yyyy_MM_dd";
    private final String projectName = "Toperate";
    private final String picturePath = "picUpload/ticket/";
    @Override
    public JsonData upload(MultipartFile file) {
        InputStream input = null;
        OutputStream output = null;
        OutputStream output1 = null;
        try {
            //取得类路径
            String classPath = this.getClass().getResource("/").getPath();
            String localRootPath = classPath.substring(0, classPath.indexOf(projectName) + projectName.length() + 1);
            String targetRootPath = classPath.substring(0,classPath.lastIndexOf(projectName) + projectName.length() + 1);
            //本地文件
            String dir = localRootPath + getDir();
            //target文件
            String targetDir = targetRootPath + picturePath + new SimpleDateFormat(FILE_DIR_FORMAT).format(new Date());
            //公共区域start
            String fileName = file.getOriginalFilename();
            String fileSuffix = FileUtils.getSuffix(fileName);
            String newFileName = getRandomName() + "." + fileSuffix;
            //end
            String fullFile = dir + File.separator + newFileName;
            String targetFullFile = targetDir +File.separator + newFileName;
            File dirFile = new File(dir);
            File targetDirFile = new File(targetDir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            if (!targetDirFile.exists()){
                targetDirFile.mkdirs();
            }
            File localFile = new File(fullFile);
            //target目标文件
            File targetFile = new File(targetFullFile);
            input = file.getInputStream();
            output = new FileOutputStream(localFile);
            //输入到target文件夹输出对象
            output1 = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = input.read(buffer)) > 0) {
                output.write(buffer, 0, len);
                output1.write(buffer, 0, len);
            }
            JsonData resData = JsonData.success(PropertiesUtil.getProperty("baseUrl") + "/" + new SimpleDateFormat
                    (FILE_DIR_FORMAT).format(new Date()) + "/" + newFileName, newFileName);
            return resData;
        } catch (Exception e) {
            return JsonData.fail("上传图片异常:" + e.getMessage());
        }finally {
            try {
                if (output1 != null)
                    output1.close();
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    String getLocalDir(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("") + "/upload/" + new SimpleDateFormat
                (FILE_DIR_FORMAT).format(new Date());
    }

    String getDir() {
        try {
            String fileDir = PropertiesUtil.getProperty("fileDir");
            return fileDir + "/" + new SimpleDateFormat
                    (FILE_DIR_FORMAT).format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getRandomName() {
        return UUID.randomUUID().toString().replaceAll("-", StringUtils.EMPTY);
    }

}
